package com.lhkj.ct.base.utils;

import cn.hutool.core.text.AntPathMatcher;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 *  url工具类
 */
public class UrlUtil {

    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    public static boolean anyMatches(String url, List<String> patterns) {
        if (StringUtils.isEmpty(url) || CollectionUtils.isEmpty(patterns)){
            return false;
        }
        for (String pattern : patterns) {
            if (isMatch(pattern, url)){
                return true;
            }
        }
        return false;
    }

    public static boolean isMatch(String pattern, String url) {
        return ANT_PATH_MATCHER.match(pattern, url);
    }

    public static String getParameters(String urlString, String paramName) {
        return Optional.of(getParameters(urlString)).map(m -> m.get(paramName)).orElse("");
    }

    public static Map<String, String> getParameters(String urlString) {
        Map<String, String> parameters = new HashMap<>();
        try {
            URL url = new URL(urlString);
            String query = url.toString().split("\\?")[1];
            if (query != null) {
                String[] pairs = query.split("&");
                for (String pair : pairs) {
                    String[] keyValue = pair.split("=");
                    if (keyValue.length == 2) {
                        String key = URLDecoder.decode(keyValue[0], "UTF-8");
                        String value = URLDecoder.decode(keyValue[1], "UTF-8");
                        parameters.put(key, value);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return parameters;
    }
}
